let Promise = require('bluebird');
let fs = require('fs');
let xml2js = require('xml2js');
let tpl = require('../wechat/tpl');


exports.parseXMLAsync = function(xml) {  //XML格式转成对象格式
    return new Promise((resolve,reject) => {
        xml2js.parseString(xml, {trim: true},(err,content) => {
            if(err) reject(err);
            else resolve(content);
        })
    })
}


exports.formatMassege = function(result) {  //XML格式转成的对象格式，进行格式化
    var message = {};
    if(typeof result === 'object') {
        var keys = Object.keys(result);
        for(var i = 0; i < keys.length; i++) {
            let key = keys[i];
            let val = result[keys[i]];
            if(!(val instanceof Array) || val.length === 0)  {
                continue
            }
            if(val.length === 1) {
                let item = val[0]
                if(typeof item === 'object') {
                    message[key] = formatMassege(item);
                }else {
                    message[key] = (item || '').trim();
                }
            }else {
                message[key] = [];
                for(var j = 0, k = item.length; j < k; j++) {
                    message[key].push(formatMassege(item[j]))
                }
            }
        }
    }
    return message;
}


exports.readFileAsync = function(fpath,encoding) {
    return new Promise((resolve,reject) => {
        fs.readFile(fpath,encoding, (err,content) => {
            if(err) reject(err);
            else resolve(content);
        })
    })
}

exports.writeFileAsync = function(fpath,content) {
    return new Promise((resolve,reject) => {
        fs.writeFile(fpath,content, (err) => {
            if(err) reject(err);
            else resolve();
        })
    })
}

exports.tpl = function(content,message) {
    let info = {};
    let type = 'text';
    let fromUserName = message.FromUserName;
    let toUserName = message.ToUserName;
    if(Array.isArray(content)) {
        type = 'news'
    }
    type = content.type || type;
    info.content = content;
    info.msgType = type;
    info.createTime = new Date().getTime();
    info.toUserName = fromUserName;
    info.fromUserName = toUserName;
    return tpl.compiled(info);
}